package com.cl.util;

import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * 系统时间工具类
 * 
 */
public class DateTimeUtils {

	/** 缺省日期格式yyyy-MM-dd */
	public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
	/** 缺省时间格式HH:mm:ss */
	public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
	/** 缺省月格式MONTH */
	public static final String DEFAULT_MONTH = "MONTH";
	/** 缺省年格式YEAR */
	public static final String DEFAULT_YEAR = "YEAR";
	/** 缺省日格式DAY */
	public static final String DEFAULT_DATE = "DAY";
	/**
	 * 缺省日期格式HOUR
	 */
	public static final String DEFAULT_HOUR = "HOUR";
	/**
	 * 缺省日期格式MINUTE
	 */
	public static final String DEFAULT_MINUTE = "MINUTE";
	/** 缺省长日期格式,精确到秒yyyy-MM-dd HH:mm:ss */
	public static final String DEFAULT_DATETIME_FORMAT_SEC = "yyyy-MM-dd HH:mm:ss";
	public static final String FILE_NAME_DATE = "yyyyMMddHHmmssSSS";

	/**
	 * 将秒转换成HH:mm:ss
	 * @param sec
	 * @return
	 */
	public static String secToTime(Long sec){
		if(sec == null){
			return "00:00:00";
		}
		StringBuffer time = new StringBuffer();
		long h = sec/3600;
		long m = sec%3600/60;
		long s = sec%3600%60;
		time.append((h < 10) ? "0"+h : h).append(":");
		time.append((m < 10) ? "0"+m : m).append(":");
		time.append((s < 10) ? "0"+s : s);
        return time.toString();
	}
	
	/**
	 * 验证日期格式
	 * @param dateStr
	 * @param format
	 * @return
	 */
	public static boolean checkDataType(String dateStr,String format){
		try {
			SimpleDateFormat formatter = new SimpleDateFormat(format);
			formatter.parse(dateStr);
			return true;
		} catch (Exception e) {
			return false;
		}

	}

	/**
	 * 功能 ： 字符串(yyyy-MM-dd HH:mm:ss)返回时间
	 * 
	 * @param time
	 * @return
	 */
	public static Date stringToDateTime(String time) {
		Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(
				DateTimeUtils.DEFAULT_DATETIME_FORMAT_SEC);
		try {
			date = formatter.parse(time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	/**
	 * 
	 * 功能 ： 返回时间字符串(yyyyMMddHHmmss)
	 */
	public static String getFileNameDate() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(
				DateTimeUtils.FILE_NAME_DATE);
		String dateString = formatter.format(currentTime);
		return dateString;
	}

	/**
	 * 
	 * 功能 ： 返回时间字符串(HH:mm:ss)
	 */
	public static String getNowTime() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(
				DateTimeUtils.DEFAULT_TIME_FORMAT);
		String dateString = formatter.format(currentTime);
		return dateString;
	}

	/**
	 * 
	 * 功能 ： 返回时间字符串(yyyy-MM-dd HH:mm:ss)
	 */
	public static String getNowDateTime() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(
				DateTimeUtils.DEFAULT_DATETIME_FORMAT_SEC);
		String dateString = formatter.format(currentTime);
		return dateString;
	}

	/**
	 * 
	 * 功能 ： 返回日期字符串("yyyy-mm-dd hh:ss:mm")的年
	 */
	public static int getYear(String s) {
		try {
			return Integer.parseInt(s.substring(0, 4));
		} catch (Exception e) {
			return 1970;
		}
	}

	/**
	 * 根据一个日期，返回是星期几的字符串
	 */
	public static String getWeek(String sdate) {
		// 再转换为时间
		Date date = strToDate(sdate);
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		// int hour=c.get(Calendar.DAY_OF_WEEK);
		// hour中存的就是星期几了，其范围 1~7
		// 1=星期日 7=星期六，其他类推
		return new SimpleDateFormat("EEEE").format(c.getTime());
	}

	// 返回日期型时间
	public static Date strToDate(String strDate) {
		SimpleDateFormat formatter = new SimpleDateFormat(
				DateTimeUtils.DEFAULT_DATETIME_FORMAT_SEC);
		ParsePosition pos = new ParsePosition(0);
		Date strtodate = formatter.parse(strDate, pos);
		return strtodate;
	}

	/**
	 * 获取当前时间
	 * 返回时间字符串(yyyy-MM-dd)
	 * @return
	 */
	public static String getNowDate() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(
				DateTimeUtils.DEFAULT_DATE_FORMAT);
		String dateString = formatter.format(currentTime);
		return dateString;
	}

	/**
	 * 
	 * 功能 ：两个时间间隔，对开始时间和结束时间大小无要求
	 */
	public static long getTimeInterval(String startTime, String endTime,String type) {

		try {

			java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(type);

			java.text.SimpleDateFormat endformatter = new java.text.SimpleDateFormat(type);

			Calendar rightNow = Calendar.getInstance();

			Calendar endrightNow = Calendar.getInstance();

			Date startTempdate = formatter.parse(startTime);

			Date endTempdate = endformatter.parse(endTime);

			rightNow.setTime(startTempdate);
			endrightNow.setTime(endTempdate);

			Long start = rightNow.getTime().getTime();
			Long end = endrightNow.getTime().getTime();
			Long result = end - start;
			return result;

		} catch (Exception e) {

			return 0;
		}
	}

	/**
	 * 
	 * 功能 ：通过季度返回月份数组
	 */
	public static Integer[] getMonthBySeason(int season) {

		try {
			Integer[] month = new Integer[3];
			switch (season) {
			case 1:
				month[0] = 1;
				month[1] = 2;
				month[2] = 3;
				break;
			case 2:
				month[0] = 4;
				month[1] = 5;
				month[2] = 6;
				break;
			case 3:
				month[0] = 7;
				month[1] = 8;
				month[2] = 9;
				break;
			case 4:
				month[0] = 10;
				month[1] = 11;
				month[2] = 12;
				break;

			default:
				break;
			}

			return month;
		} catch (Exception e) {

			return new Integer[0];
		}

	}

	/**
	 * 
	 * 功能 ：通过月份返回季度
	 * 
	 */
	public static int getSeasonByMonth(int month) {

		try {
			int season = -1;
			switch (month) {
			case 1:
				season = 1;
				break;
			case 2:
				season = 1;
				break;
			case 3:
				season = 1;
				break;
			case 4:
				season = 2;
				break;
			case 5:
				season = 2;
				break;
			case 6:
				season = 2;
				break;
			case 7:
				season = 3;
				break;
			case 8:
				season = 3;
				break;
			case 9:
				season = 3;
				break;
			case 10:
				season = 4;
				break;
			case 11:
				season = 4;
				break;
			case 12:
				season = 4;
				break;
			default:
				season = 0;
				break;
			}

			return season;

		} catch (Exception e) {

			return 0;
		}

	}

	/**
	 * 功能 ：对于给定的时间增加天数/月数/年数后的日期,按指定格式输出
	 * 
	 * @param date
	 *            时间
	 * @param type
	 *            增加的类型
	 * @param interval
	 *            增加的值
	 * @param strFormat
	 *            时间类型
	 * @return
	 */
	public static String getEndTime(String date, String type, int interval,
			String strFormat) {

		try {

			java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(
					strFormat);

			Calendar rightNow = Calendar.getInstance();
			Date tempdate;
			tempdate = formatter.parse(date);

			rightNow.setTime(tempdate);

			int intField = 0;
			String tmpField = type.toUpperCase();

			intField = Calendar.DATE;
			if (tmpField.equals(DEFAULT_YEAR)){
				intField = Calendar.YEAR;
			}else if (tmpField.equals(DEFAULT_MONTH)){
				intField = Calendar.MONTH;
			}else if (tmpField.equals(DEFAULT_DATE)){
				intField = Calendar.DATE;
			}else if (tmpField.equals(DEFAULT_MINUTE)){
				intField = Calendar.MINUTE;
			}

			rightNow.add(intField, interval);
			String day = formatter.format(rightNow.getTime());

			return day;

		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 根据指定日期得到是当月的第几周
	 */
	public static int getWeekNumOfMonth(String strDate) {
		Calendar cal = null;
		cal = new GregorianCalendar();
		int yy = Integer.parseInt(strDate.substring(0, 4));
		int mm = Integer.parseInt(strDate.substring(5, 7)) - 1;
		int dd = Integer.parseInt(strDate.substring(8, 10));
		cal.set(yy, mm, dd);
		int iWeekNum = cal.get(Calendar.WEEK_OF_MONTH);
		return iWeekNum;
	}

	/**
	 * 根据指定日期得到是当年的第几周
	 * 
	 */
	public static int getWeekNumOfYear(String strDate) {
		Calendar cal = null;
		cal = new GregorianCalendar();
		int yy = Integer.parseInt(strDate.substring(0, 4));
		int mm = Integer.parseInt(strDate.substring(5, 7)) - 1;
		int dd = Integer.parseInt(strDate.substring(8, 10));
		cal.set(yy, mm, dd);
		int iWeekNum = cal.get(Calendar.WEEK_OF_YEAR);
		return iWeekNum;
	}

	public static int getAge(Date birthDay) {
		Calendar cal = Calendar.getInstance();

		if (cal.before(birthDay)) {
			return 0;
		}
		int yearNow = cal.get(Calendar.YEAR);
		int monthNow = cal.get(Calendar.MONTH);
		int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
		cal.setTime(birthDay);

		int yearBirth = cal.get(Calendar.YEAR);
		int monthBirth = cal.get(Calendar.MONTH);
		int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

		int age = yearNow - yearBirth;

		if (monthNow <= monthBirth) {
			if (monthNow == monthBirth) {
				if (dayOfMonthNow < dayOfMonthBirth)
					age--;
			} else {
				age--;
			}
		}
		System.out.println("age:" + age);
		return age;
	}

	/**
	 * 获得当前日期与本周一相差的天数
	 * 
	 * @return
	 */
	private static int getMondayPlus() {
		Calendar cd = Calendar.getInstance();
		// 获得今天是一周的第几天，星期日是第一天，星期二是第二天......
		int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK);
		if (dayOfWeek == 1) {
			return -6;
		} else {
			return 2 - dayOfWeek;
		}
	}

	/**
	 * 获得当前周- 周一的日期
	 * 
	 * @return
	 */
	public static String getCurrentMonday() {
		int mondayPlus = getMondayPlus();
		GregorianCalendar currentDate = new GregorianCalendar();
		currentDate.add(GregorianCalendar.DATE, mondayPlus);
		Date monday = currentDate.getTime();
		SimpleDateFormat df = new SimpleDateFormat(
				DateTimeUtils.DEFAULT_DATE_FORMAT);
		String preMonday = df.format(monday);
		return preMonday + " 00:00:00";
	}

	/**
	 * 获得当前周- 周日 的日期
	 * 
	 * @return
	 */
	public static String getPreviousSunday() {
		int mondayPlus = getMondayPlus();
		GregorianCalendar currentDate = new GregorianCalendar();
		currentDate.add(GregorianCalendar.DATE, mondayPlus + 6);
		Date monday = currentDate.getTime();
		SimpleDateFormat df = new SimpleDateFormat(
				DateTimeUtils.DEFAULT_DATE_FORMAT);
		String preMonday = df.format(monday);
		return preMonday + " 23:59:59";
	}

	public static String dateToStr(Date date, String format) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		String dateString = formatter.format(date);
		return dateString;
	}


	/**
	 * 将时间转换为 刚刚，分钟前，小时前，几天前
	 * @param dateString 时间格式要为yyyy-MM-dd HH:mm:ss
	 * @param type 1.返回( 刚刚，分钟前，小时前，几天前) 2.返回(MM-dd HH:mm) 默认1
	 * @return
	 */
	public static String format(String dateString , int type) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		Date date;
		try {
			if (null != dateString && !"".equals(dateString)) {
				date = format.parse(dateString);
				if(type == 1){
					long time = System.currentTimeMillis()-date.getTime();
					if ((time)<(5*60*1000)) {//<5分钟，则展示“刚刚”
						dateString = "刚刚";
					}else if (time>=(5*60*1000)&& time<(60*60*1000)){//5<x<60分钟，则展示“X分钟前”
						long time1 = time/(60*1000);
						dateString = time1+"分钟前";
					}else if (time>=(60*60*1000) && time<(24*60*60*1000)){//<24小时，则展示“X小时前”
						long time1 = time/(60*60*1000);
						dateString = time1 +"小时前";
					}else if(time>=(1*24*60*60*1000L) && time <= (7*24*60*60*1000L)){
						dateString = time/(24*60*60*1000L)+"天前";
					}else if(time>=(7*24*60*60*1000L) && time <= (30*24*60*60*1000L)){
						dateString = time/(7*24*60*60*1000L)+"周前";
					}else if(time>=(30*24*60*60*1000L) && time <= (12*30*24*60*60*1000L)){
						dateString = time/(30*24*60*60*1000L)+"月前";
					}else{
						dateString = format1.format(date);
					}
				}else{
					dateString = format1.format(date);
				}
			}else{
				return null;
			}
		} catch (ParseException e) {

		}
		return dateString;
	}

	/**
	 * 获取当月第一天日期
	 * @date 2017-4-5 上午11:17:13
	 * @author soon
	 * @description	
	 * @return
	 */
	public static String getCurMonthFirstDay(){

		SimpleDateFormat minSecFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
		Calendar   cal_1=Calendar.getInstance();//获取当前日期 
		cal_1.add(Calendar.MONTH, 0);
		cal_1.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 
		String firstDay = minSecFormat.format(cal_1.getTime());
		return firstDay;

	}

	/**
	 * 获取当月最后一天日期
	 * @date 2017-4-5 上午11:17:34
	 * @author soon
	 * @description	
	 * @return
	 */
	public static String getCurMonthLastDay(){

		SimpleDateFormat minSecFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
		Calendar   cal_1=Calendar.getInstance();//获取当前日期 
		cal_1.add(Calendar.MONTH, 0);
		cal_1.set(Calendar.DAY_OF_MONTH, cal_1.getActualMaximum(Calendar.DAY_OF_MONTH));//设置为1号,当前日期既为本月第一天 
		String firstDay = minSecFormat.format(cal_1.getTime());
		return firstDay;

	} 

	/**
	 * 得到几分钟后的时间
	 * @param minute
	 * @return
	 */
	public static String getTimeByMinute(int minute) {

		Calendar calendar = Calendar.getInstance();

		calendar.add(Calendar.MINUTE, minute);

		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
	}

}
